import { File } from "formidable";
import path from "path";
import fs from "fs/promises";
import config from "@/app/config";
// 文件信息类型定义
export interface FileInfo {
  filename: string;
  originalName: string;
  url: string;
  size: number;
  mimetype: string;
  category?: string;
  uploadTime: string;
}

class uploadService {
  /**
   * 处理单文件上传
   */
  async handleSingleFile(file: File): Promise<FileInfo> {
    // 1. 验证文件类型（示例：只允许图片）
    const allowedMimeTypes = ["image/jpeg", "image/png", "image/gif"];
    if (!allowedMimeTypes.includes(file.mimetype!)) {
      // 若验证失败，先删除已上传的临时文件
      await fs.unlink(file.filepath);
      throw new Error("不支持的文件类型，仅允许 jpg、png、gif");
    }

    // 2. 生成文件访问 URL
    const url = `uploads/${file.newFilename}`;

    // 3. 可选：记录文件信息到数据库（此处简化为内存对象）
    const fileInfo: FileInfo = {
      filename: file.newFilename,
      originalName: file.originalFilename || "",
      url,
      size: file.size,
      mimetype: file.mimetype!,
      uploadTime: new Date().toISOString(),
    };

    return fileInfo;
  }

  /**
   * 批量删除文件
   */
  async deleteFiles(filenames: string[]): Promise<{ deleted: number }> {
    let deletedCount = 0;

    for (const filename of filenames) {
      if (!filename) continue;
      const filePath = path.join(config.UPLOAD_DIR, filename.split("/")[1]);
      try {
        // 先检查文件是否存在
        await fs.access(filePath);
        // 删除文件
        await fs.unlink(filePath);
        deletedCount++;
      } catch (error) {
        console.warn(`删除文件 ${filename} 失败：${(error as Error).message}`);
        // 不中断循环，继续删除其他文件
      }
    }

    return { deleted: deletedCount };
  }
}

export default new uploadService();
